import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入页面组价
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import Detail from '@/views/Detail/Detail.vue'
import Edit from '@/views/Edit/Edit.vue'
import Search from '@/views/Search/Search.vue'
import SearchResult from '@/views/SearchResult/SearchResult.vue'
import Message from '@/views/Message/Message.vue'
// 导入模块组件
import Home from '@/components/Home/Home.vue'
import Mine from '@/components/Mine/Mine.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/main',
    name: 'Main',
    component: Main,
    redirect: '/main/home',
    children: [
      {
        path: 'mine',
        name: 'Mine',
        component: Mine
      },
      {
        path: 'home',
        name: 'Home',
        component: Home,
        meta: { keepAlive: true, isRecord: true, top: 0 }
      },
      {
        path: 'message',
        name: 'Message',
        component: Message,
      }
    ]
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: Detail,
    meta: { isRecord: true, top: 0 }
  },
  {
    path: '/edit',
    name: 'Edit',
    component: Edit
  },
  {
    path: '/search',
    name: 'Search',
    component: Search
  },
  {
    path: '/search/:kw',
    component: SearchResult,
    name: 'search-result',
    props: true,
    meta: { keepAlive: true, isRecord: true, top: 0 }
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/main/mine') {
    if (token) {
      next()
    } else {
      next({ name: 'Login' })
    }
  }
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 如果当前的路由的元信息中，isRecord 的值为 true
  if (to.meta.isRecord) {
    setTimeout(() => {
      // 则把元信息中的 top 值设为滚动条纵向滚动的位置
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})

export default router
